package com.naizhuai.ui.task;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.naizhuai.Model.AccountHelper;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.TaskActionApiStore;
import com.naizhuai.network.exception.ValidateException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.ChosenChargeJoinAdapterHolder;
import com.naizhuai.ui.adapter.GridSpacingItemDecoration;
import com.naizhuai.ui.adapter.SpacesItemDecoration;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.entity.AddTask;
import com.naizhuai.ui.entity.AddTaskPage;
import com.naizhuai.ui.entity.TaskTypeBean;
import com.naizhuai.ui.mianbusiness.setting.UserListChosenActivity;
import com.naizhuai.ui.task.adapter.LabelDailogAdapter;
import com.naizhuai.ui.task.adapter.TaskReasonAdapter;
import com.naizhuai.ui.task.adapter.TaskTypeAdapter;
import com.naizhuai.ui.task.deliverentity.TaskType;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ViewUtils;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.api.widget.Widget;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.naizhuai.ui.mianbusiness.target.TargetCreateActivity.CHARGE_KEY;
import static com.naizhuai.ui.mianbusiness.target.TargetCreateActivity.CHOSE_CHARGE;
import static com.naizhuai.ui.mianbusiness.target.TargetCreateActivity.CREATE_TARGET_PAGER;

// TODO: 2018/4/9 引入MVP模式 代码解耦
public class TaskReleaseActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    public static void start(Context context, String goalId) {
        Intent intent = new Intent(context, TaskReleaseActivity.class);
        intent.putExtra(GOALID, goalId);
        context.startActivity(intent);
    }

    @BindView(R.id.release)
    Button release;
    @BindView(R.id.reason_list)
    RecyclerView reasonList;
    @BindView(R.id.task_cycle)
    RecyclerView taskCycle;
    @BindView(R.id.charged_thumb)
    CircleImageView chargedThumb;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.taskBudget)
    EditText taskBudget;
    @BindView(R.id.bugget_money)
    TextView buggetMoney;
    @BindView(R.id.task_name)
    EditText taskName;
    @BindView(R.id.ed_keyresult)
    EditText edKeyresult;
    @BindView(R.id.task_status)
    EditText taskStatus;
    @BindView(R.id.task_target)
    EditText taskTarget;
    @BindView(R.id.change_charge_user_btn)
    ImageView changeChargeUserBtn;
    private ArrayList<String> imageList;
    private static final String GOALID = "goalId";
    private TaskTypeAdapter mTaskCircleTypeAdapter;
    private TaskReasonAdapter mTaskReasonAdapter;
    private static final int COLUMN = 4;
    private TaskActionApiStore mTaskActionApiStore;
    private TaskType mTaskCircleType;
    private String tempUserId;
    private String goalId;

    /**
     * 目标对象 从目标页面传来
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    private void initData() {
        initTaskExplain();
        initTaskCycle();
        initNetData();
    }

    private void initNetData() {
        if (mTaskActionApiStore == null) {
            mTaskActionApiStore = TaskActionApiIml.getInstance();
        }

//        //获取流程工具包
//        mTaskActionApiStore.getTaskFlowList()
//                .subscribe(new Observer<TaskFlowMethod>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        NaizhuAILog.e(e.getMessage());
//                    }
//
//                    @Override
//                    public void onNext(TaskFlowMethod flows) {
//                        if (flows != null) {
//                            mTaskFlows.addAll(flows.getMethodList());
//                            FlowSettingActivity.mCircleList=setTaskType(flows.getCircleList());
//                        }
//
//                    }
//                });
        goalId = getStrExtra(GOALID);
        if (!TextUtils.isEmpty(goalId)) {
            mTaskActionApiStore.getAddTaskPage(AccountHelper.getComPanyid(), goalId)
                    .subscribe(new NetWorkObserver<AddTaskPage>() {
                        @Override
                        protected void onFail(String errormsg) {
                            shortToast(errormsg);
                        }

                        @Override
                        protected void onSuccess(AddTaskPage result) {
                            buggetMoney.setText(result.getGoalBudget());
                            mTaskCircleTypeAdapter.setTypeList(setTaskType(result.getCircleTypeList()));
                        }
                    });
        }
    }


    private void checkInput() throws ValidateException {
        if (TextUtils.isEmpty(ViewUtils.text(taskName))) {
            throw new ValidateException(getString(R.string.please_task_name));
        }
        String taskexplain = mTaskReasonAdapter.getTaskString();
        if (TextUtils.isEmpty(taskexplain)) {
            throw new ValidateException(getString(R.string.taskexplain_not_null));
        }
        if (TextUtils.isEmpty(ViewUtils.text(edKeyresult))) {
            throw new ValidateException(getString(R.string.task_please_input_keyresult));
        }

        if (TextUtils.isEmpty(ViewUtils.text(taskStatus))) {
            throw new ValidateException(getString(R.string.task_please_input_status));
        }

        if (TextUtils.isEmpty(ViewUtils.text(taskTarget))) {
            throw new ValidateException(getString(R.string.task_please_input_target));
        }

        if (TextUtils.isEmpty(mTaskCircleTypeAdapter.getSelectedJson())) {
            throw new ValidateException(getString(R.string.taskcircletype_not_null));
        }

        if (TextUtils.isEmpty(tempUserId)) {
            throw new ValidateException(getString(R.string.task_please_select_leader));
        }

        if (TextUtils.isEmpty(ViewUtils.text(taskBudget))) {
            throw new ValidateException(getString(R.string.task_please_input_budget));
        }

         int taskBudgetMoney=Integer.parseInt(ViewUtils.text(taskBudget));
         int realBudgetMoney=Integer.parseInt(ViewUtils.text(buggetMoney));
         if (taskBudgetMoney>realBudgetMoney){
             throw new ValidateException(getString(R.string.budget_surpass));
         }
    }

    private ArrayList<TaskType> setTaskType(List<TaskTypeBean> types) {
        ArrayList<TaskType> list = new ArrayList<>();
        if (types != null) {
            for (TaskTypeBean typeBean : types) {
                list.add(new TaskType(typeBean.getLabel(), typeBean.getValue(), typeBean.getEnable()));
            }
        }
        return list;
    }

//    private void initView() {
//        toolbar.setTitle("任务名:我的家在东北");
//        initTaskType();
//        initTaskExplain();
//
//        selectorAppointor.setOnClickListener(view -> {
//            Intent intent = new Intent(TaskReleaseActivity.this, SearchUserActivity.class);
//            startActivityForResult(intent, REQUEST_CODE);
//        });
//
//        detailsArrange.setOnClickListener(view ->
//            mArrangeDialog = DialogUtils.showNoBtnDialog(TaskReleaseActivity.this,
//                            getString(R.string.step_utilpackage), initTaskFlowView())
//        );
//        tvRelease.setOnClickListener(view -> {
//            try {
//                checkInput();
//                submitTask();
//            } catch (Exception e) {
//                shortToast(e.getMessage());
//            }
//        });
//
//    }

//    private View initTaskFlowView() {
//            TaskFlowAdapter mFlowAdapter = new TaskFlowAdapter(mTaskFlows);
//            mFlowAdapter.getOnClickSubject().subscribe(flow -> {
//                if (mArrangeDialog!=null&&mArrangeDialog.isShowing()){
//                    mArrangeDialog.dismiss();
//                }
//                Intent intent = new Intent(TaskReleaseActivity.this, FlowSettingActivity.class);
//                intent.putExtra(FlowSettingActivity.flowlist, flow);
//                startActivity(intent);
//            }
//            );
//            View dialogView = LayoutInflater.from(this).inflate(R.layout.show_stepinfo, null);
//            GridLayoutManager layoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
//            RecyclerView mTaskFlowView = dialogView.findViewById(R.id.joinPeopleList);
//            mTaskFlowView.setLayoutManager(layoutManager);
//            mTaskFlowView.addItemDecoration(new GridSpacingItemDecoration(4, getResources().getDimensionPixelSize(R.dimen.padding_default_min), false));
//            mTaskFlowView.setAdapter(mFlowAdapter);
//
//        return dialogView;
//    }

    private void initTaskCycle() {
        mTaskCircleTypeAdapter = new TaskTypeAdapter();
        mTaskCircleTypeAdapter.setSelected(TaskTypeAdapter.SERIALSELECTED);
        GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN, GridLayoutManager.VERTICAL, false);
        taskCycle.setNestedScrollingEnabled(false);
        taskCycle.setLayoutManager(layoutManager);
        taskCycle.addItemDecoration(new GridSpacingItemDecoration(COLUMN, getResources().getDimensionPixelSize(R.dimen.padding_default_min), false));
        taskCycle.setAdapter(mTaskCircleTypeAdapter);
//        mTaskCircleTypeAdapter.getSelectedClicks()
//                .subscribe(type ->
//                        mTaskCircleType = type
//                );

    }

//    private void initUnitPop(List<AddTaskPage.CompanyUnitRulesBean> flows) {
//        mPopup = new ListPopupWindow(this);
//        ArrayAdapter<AddTaskPage.CompanyUnitRulesBean> mPopUnitAdapter = new ArrayAdapter(this, android.R.layout.test_list_item);
//        mPopUnitAdapter.addAll(flows);
//        mPopup.setAdapter(mPopUnitAdapter);
//        mPopup.setWidth(LayoutParams.WRAP_CONTENT);
//        mPopup.setHeight(LayoutParams.WRAP_CONTENT);
//        mPopup.setModal(true);
//        mPopup.setOnItemClickListener((parent, view, position, id) -> {
//            mPopup.dismiss();
//            unitRule = flows.get(position);
//            convertUnitText.setText(unitRule.toString());
//        });
//        convertUnit.setOnClickListener(view -> {
//            mPopup.setAnchorView(view);
//            mPopup.show();
//        });
//    }

    private void initTaskExplain() {
        ArrayList<String> list1 = new ArrayList<>();
        list1.add("");
        list1.add("");
        list1.add("");
        list1.add("");
        list1.add("");
        mTaskReasonAdapter = new TaskReasonAdapter(list1);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        reasonList.setNestedScrollingEnabled(false);
        reasonList.setLayoutManager(layoutManager);
        reasonList.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.padding_default_min)));
        reasonList.setAdapter(mTaskReasonAdapter);
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_task_release;
    }


    @OnClick(R.id.change_charge_user_btn)
    public void onSelectPerson() {
        Intent intent = new Intent(this, UserListChosenActivity.class);
        intent.putExtra(ChosenChargeJoinAdapterHolder.ENTER_TYPE_KEY, ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_MANAGE);
        intent.putExtra(ConstantsState.CHOSEN_USER_TYPE_KEY, ConstantsState.CHOSEN_TASK_USER_TYPE);
        intent.putExtra(ConstantsState.SERVER_ID_KEY, goalId);
        intent.putExtra(UserListChosenActivity.ENTER_CHOSEN_TYPE_KEY, UserListChosenActivity.ENTER_CHOSEN_TYPE_LIMITED);
        startActivityForResult(intent, CREATE_TARGET_PAGER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != CREATE_TARGET_PAGER)
            return;
        switch (resultCode) {
            case CHOSE_CHARGE:
                PersonUserBean result = (PersonUserBean) data.getSerializableExtra(CHARGE_KEY);
                ViewUtils.showAvatorOrName(result.getUserLogoUrl(), result.getNickName(), chargedThumb);
                tempUserId = result.getUid();
                userName.setText(result.getNickName());

        }
    }

    @OnClick(R.id.release)
    public void onRelease() {
        try {
            checkInput();
            submitTask();
        } catch (ValidateException e) {
            shortToast(e.getMessage());
        }
    }

    private void submitTask() {
        //获取任务名称 关键结果 换算单位  现状 目标 任务周期 任命人的ID
        AddTask addTask = new AddTask()
                .setName(ViewUtils.text(taskName))
                .setGoalId(goalId)
                .setLeaderUid(tempUserId)
                .setDetail(mTaskReasonAdapter.getTaskString())
                .setWeekControl(mTaskCircleTypeAdapter.getSelectedJson())
                .setBudget(ViewUtils.text(taskBudget))
                .setKeyResult(ViewUtils.text(edKeyresult))
                .setCurrentValue(ViewUtils.text(taskStatus))
                .setGoalValue(ViewUtils.text(taskTarget));
        showWaitDiaLog();
        mTaskActionApiStore.addTaskPage(addTask)
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(String result) {
                        hideWaitDialog();
                        if ("0".equals(result)) {
                            shortToast(getString(R.string.sendfail));
                        } else {
                            shortToast(getString(R.string.addtask_success));
                            finish();
                        }
                    }
                });
    }

    @OnClick(R.id.reference)
    public void onReferenceClicked() {
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        View view=View.inflate(this,R.layout.dialog_list,null);
        ListView listView=view.findViewById(R.id.tv_list);
        TextView sure=view.findViewById(R.id.tv_sure);
        TextView title=view.findViewById(R.id.tv_title);
        title.setText(getString(R.string.keyresult_hint));
        List<String> strings= Arrays.asList(getResources().getStringArray(R.array.keyresult_array));
        listView.setAdapter(new LabelDailogAdapter(this,strings));
        normalDialog.setView(view);
        AlertDialog dialog=normalDialog.show();
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onBackPressedWithoutDialog() {
        DialogUtils.showSureDialog(this, getString(R.string.lost_data), dialog -> finish());
    }
}
